<?php

namespace App\Task\Guild;

use App\Model\CoinLog;
use App\Model\Guild\GuildAccountDaily;
use App\Model\Guild\GuildHost;
use App\Model\Guild\GuildHostAccountDaily;
use App\Model\Guild\GuildHostTag;
use App\Model\Guild\GuildManage;
use App\Model\UserActLog;
use App\Model\UserProfile;
use Hyperf\Crontab\Annotation\Crontab;

/**
 * 公会结算
 * @Crontab(name="GuildAccountTask", rule="*\/3 * * * *", callback="execute", memo="公会结算", enable=true)
 */
class GuildAccountTask
{
    public function execute()
    {
        $startDay = 0;
        $endDay = 0;
        //查找所有公会
        $guilds = GuildManage::getGuilds();
        for ($day = $startDay; $day >= $endDay; $day--) {
            $this->runDaily($guilds, $day);
        }
    }

    function runDaily($guilds = [], $day = 0)
    {
        //一天前5分钟内
        if (time() - strtotime(date('Y-m-d')) < 600) {
            $day++;
        }
        $this->startTime = date('Y-m-d', strtotime("-{$day} day"));
        $nextDay = $day - 1;
        $this->endTime = date('Y-m-d', strtotime("-{$nextDay} day"));
        log_info(__CLASS__ . "==Start:{$this->startTime}==End:{$this->endTime}");
        array_walk($guilds, function ($guild) {
            //获取公会主播
            $this->hostInfo = GuildHost::getHostIds($guild['id']);
            if (empty($this->hostInfo)) return;
            $hostIds = array_keys($this->hostInfo);
            //公会结算
            $incomeHostIds = $this->runGuildAccount($guild, $hostIds);
            log_info(__CLASS__ . "==GuildId:{$guild['id']}==IncomeHosts:" . count($incomeHostIds));
            //公会主播结算
            $this->runHostAccount($guild, $incomeHostIds);
            //代理标签主播结算
            // $this->runHostTagAccount($guild, $incomeHostIds);
            //主播累计分成
            // $this->runHostTotal($guild, $hostIds);
        });
    }

    /**
     * 公会结算
     */
    function runGuildAccount($guild = [], $hostIds = [])
    {
        return $incomeHostIds = GuildAccountDaily::guildAccount(
            $guild,
            $hostIds,
            $this->startTime,
            $this->endTime
        );
    }

    /**
     * 公会主播结算
     */
    function runHostAccount($guild = [], $hostIds = [])
    {
        $info = [];
        $info['dt'] = $startTime = $this->startTime;
        $endTime =  $this->endTime;
        //公会ID
        $info['guild_manage_id'] = $guild['id'];
        // $guildBindTime = $guild['created_at'];
        // $profiles = UserProfile::getUsersProfile($hostIds, true);
        $hostShareRatio = 1 - config('busi.commission.consume');
        array_walk($hostIds, function ($hostId) use (&$info, $guild, $endTime, $startTime, $hostShareRatio) {
            $info['host_id'] = $hostId;
            //语音流水
            $info['voice_turnover'] = CoinLog::getTotalConsume([$hostId], $startTime, $endTime, [CoinLog::FROM_VOICECALL_OUT, CoinLog::FROM_QUICK_VOICE_OUT]);
            //视频流水
            $info['video_turnover'] = CoinLog::getTotalConsume([$hostId], $startTime, $endTime, [CoinLog::FROM_VIDEOCALL_OUT, CoinLog::FROM_QUICK_VIDEO_OUT]);
            //私信流水
            $info['msg_turnover'] = CoinLog::getTotalConsume([$hostId], $startTime, $endTime, CoinLog::FROM_SEND_PRIVATE_MSG_OUT);
            //礼物流水
            $info['gift_turnover'] = CoinLog::getTotalConsume([$hostId], $startTime, $endTime, CoinLog::FROM_SEND_GIFT);
            //平台福利
            $info['free_turnover'] = CoinLog::getTotalIncome([$hostId], $startTime, $endTime, CoinLog::FROM_DAILY_FREE);
            //总消费流水
            $info['total_turnover'] = $info['voice_turnover'] + $info['video_turnover'] + $info['msg_turnover'] + $info['gift_turnover'] + $info['free_turnover'];

            //主播分成（语音和视频）
            $info['host_share_income'] = GuildManage::hostShareIncome($hostShareRatio, $info['total_turnover']);
            //语音分成
            $info['voice_share_income'] = GuildManage::hostShareIncome($hostShareRatio, $info['voice_turnover']);
            //视频分成（正常视频+福利通话）
            $info['video_share_income'] = GuildManage::hostShareIncome($hostShareRatio, $info['video_turnover']) + $info['free_turnover'];
            //礼物分成
            $info['gift_share_income'] = GuildManage::hostShareIncome($hostShareRatio, $info['gift_turnover']);
            //消息分成
            $info['msg_share_income'] = GuildManage::hostShareIncome($hostShareRatio, $info['msg_turnover']);
            //邀请分成
            $info['invite_recharge_income'] = CoinLog::getTotalIncome([$hostId], $startTime, $endTime, CoinLog::FROM_INVITE_RECHARGE);
            //总分成
            $info['total_share_income'] = CoinLog::getTotalIncome([$hostId], $startTime, $endTime);
            //最近上线时间
            $info['last_online_at'] = UserActLog::getLastOnlineTime($hostId, $startTime, $endTime);
            //主播签约该公会日期
            $info['binded_at'] = GuildHost::getBindTime($hostId, $guild['id']);

            log_info(__CLASS__ . "==statHostAccount==GuildId:{$guild['id']}==HostId:{$hostId}==HostShare:{$hostShareRatio}");
            //添加记录
            GuildHostAccountDaily::updateOrCreate([
                'host_id' => $info['host_id'],
                'dt' => $info['dt']
            ], $info);
        });
    }

    /**
     * 主播按标签结算
     */
    function runHostTagAccount($guild = [], $hostIds = [])
    {
        $guildId = $guild['id'];
        $hostTags = GuildHostTag::getTags($guildId);
        foreach ($hostTags as $tagId => $tagName) {
            // $hostIds = 
        }
    }

    /**
     * 主播累计收入
     */
    function runHostTotal($guild = [], $hostIds = [])
    {
        $info = [];
        $info['dt'] = $this->startTime;
        // $endTime =  $this->endTime;
        //公会ID
        $info['guild_manage_id'] = $guild['id'];

        array_walk($hostIds, function ($hostId) use (&$info, $guild) {
            //累计收入
            // $info['income_coin'] = CoinLog::getTotalIncome([$hostId]);
            //消费总流水
            $info['consume_coin'] =  CoinLog::getTotalConsume([$hostId]);
            //添加记录
            GuildHost::updateOrCreate([
                'guild_manage_id' => $guild['id'],
                'host_user_id' => $hostId,
                'status' => 1,
            ], $info);
            log_info(__CLASS__ . "==runHostTotal==GuildId:{$guild['id']}==HostId:{$hostId}==BindTime:{$this->hostInfo[$hostId]}==" . json_encode($info));
        });
    }
}
